package com.atguigu.tingshu.album.receiver;


import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.config.redis.RedisConfig;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AlbumReceiver {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;
    @Autowired
    private RedisConfig redisConfig;

    /*
    * 从mq中接收消息
    * 所以这是一个监听系统，监听mq中的消息，
    * 当有消息发送到mq中，就会触发这个方法

     监听声音，然后改变声音进度
    * @param mqVo
    * @param channel
    * @param message
    * */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK,durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(TrackStatMqVo mqVo, Channel channel, Message message){
        if (mqVo!=null){
            log.info("更新声音统计：{}", mqVo);
            //这是消费者，我们要对消费者进行幂等性处理
            //setnx::key
            String redisKey = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX+mqVo.getBusinessNo();
            //判断是否存在/尝试存入Redis
            Boolean flag =
                    redisTemplate.opsForValue().setIfAbsent(redisKey, "1", 10, TimeUnit.SECONDS);
            if (flag){//不存在
                //更新数据库
                try {
                    trackInfoService.updateTrackStat(mqVo);
                } catch (Exception e) {
                    redisTemplate.delete(redisKey);
                    //如果异常将无法处理消息发送到死信（异常）交换机->死信队列->消费者处理进入存入消费者异常消息表->人工处理
                    //获取当前消息的 唯一投递标签（delivery tag），标记不发送
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                }
            }

        }
    }





}
